package com.sbwebsocket.core.redis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sbwebsocket.core.model.bo.DirectMessageBody;
import com.sbwebsocket.core.model.bo.UnusualMessage;
import com.sbwebsocket.core.ws.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: GSJ
 * @Date: 2022/2/16
 * @Description:
 * @version: 1.0
 */
@Slf4j
public class RedisDirectMessageReceiver {

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    RedisDelayProcUnusualMessage redisDelayProcUnusualMessage;

    public void receive(String jsonMsg){
        log.info("开始接收direct消息:{}",jsonMsg);
        try {
            DirectMessageBody directMessageBody = objectMapper.readValue(jsonMsg, DirectMessageBody.class);
            List<String> sendClientIdentitys = directMessageBody.getSendClientIdentitys();
            ConcurrentHashMap<String, WebSocketServer> webSocketMap = WebSocketServer.webSocketMap;
            for (String clientKey : sendClientIdentitys) {
                WebSocketServer webSocketServer = webSocketMap.get(clientKey);
                if(null!=webSocketServer){
                    if(log.isDebugEnabled()){
                        log.debug("给客户端clientKey:{}发送消息完成！",clientKey);
                    }
                    try {
                        webSocketServer.sendMessage(directMessageBody.getBody());
                    } catch (Exception e) {
                        log.debug("client异常离线clientKey:{}",clientKey);
                        redisDelayProcUnusualMessage.save(new UnusualMessage(clientKey,directMessageBody.getBody()));
                    }
                }
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }
}
